package com.seqb.manage.subject.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.seqb.common.ResultVo;
import com.seqb.common.mybatis.WrapperHandler;
import com.seqb.exception.BdException;
import com.seqb.manage.subject.dao.SubjectClockInDao;
import com.seqb.manage.subject.dao.SubjectDao;
import com.seqb.manage.subject.domain.SubjectClockInDO;
import com.seqb.manage.subject.domain.SubjectDO;
import com.seqb.manage.subject.service.SubjectClockInService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author lilinshen
 * @title 科目打卡人数表
 * @description 请填写相关描述
 * @date 2019-11-27
 */
@Service
public class SubjectClockInServiceImpl implements SubjectClockInService {
    @Autowired
    private SubjectDao subjectDao;
    @Autowired
    private SubjectClockInDao subjectClockInDao;

    @Override
    public SubjectClockInDO get(Long id) {
        return subjectClockInDao.selectById(id);
    }

    @Override
    public Page<SubjectClockInDO> list(Map<String, Object> map) {
        if (null != map && null != map.get("pageNumber") && null != map.get("pageSize")) {
            PageHelper.startPage(Integer.valueOf(map.get("pageNumber").toString()), Integer.valueOf(map.get("pageSize").toString()));
        } else {
            PageHelper.startPage(1, Integer.MAX_VALUE);
        }
        map.put("isDelete", "0");
        return subjectClockInDao.list(map);
    }

    @Override
    public int count(Map<String, Object> map) {
        QueryWrapper queryWrapper = WrapperHandler.genQueryWrapper(map, SubjectClockInDO.class);
        return subjectClockInDao.selectCount(queryWrapper);
    }

    @Override
    @Transactional
    public int save(SubjectClockInDO subjectClockIn) {
        return subjectClockInDao.insert(subjectClockIn);
    }

    @Override
    @Transactional
    public int update(SubjectClockInDO subjectClockIn) {
        return subjectClockInDao.updateById(subjectClockIn);
    }

    @Override
    @Transactional
    public int remove(Long id) {
        return subjectClockInDao.deleteById(id);
    }

    @Override
    @Transactional
    public int batchRemove(Long[] ids) {
        return subjectClockInDao.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createDailyClockIn() {
        try {
            //获取所有的科目
            List<SubjectDO> subjectList = subjectDao.selectList(null);
            if (null == subjectList || subjectList.size() <= 0) {
                return true;
            }
            //创建每天的打卡数据
            for (SubjectDO subject : subjectList) {
                //先查询是否已存在
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("subject_id", subject.getId());
                queryWrapper.apply("to_days(create_date) = to_days(now())");
                SubjectClockInDO exist = subjectClockInDao.selectOne(queryWrapper);
                if (null != exist) {
                    continue;
                }
                //再保存数据
                SubjectClockInDO subjectClockIn = new SubjectClockInDO();
                subjectClockIn.setSubjectId(subject.getId());
                subjectClockIn.setName(subject.getName());
                subjectClockIn.setClockInNumber(0L);
                int insert = subjectClockInDao.insert(subjectClockIn);
                if (insert <= 0) {
                    throw new BdException("操作失败！");
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVo recordClockInNumber(SubjectClockInDO subjectClockIn) {
        try {
            int result = 0;
            Long subjectId = subjectClockIn.getSubjectId();
            if (null == subjectId) {
                return ResultVo.error("参数不足！");
            }
            //查找当天打卡的记录数
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("subject_id", subjectId);
            queryWrapper.apply("to_days(create_date) = to_days(now())");
            SubjectClockInDO exist = subjectClockInDao.selectOne(queryWrapper);
            if (null != exist) {
                UpdateWrapper updateWrapper = new UpdateWrapper();
                updateWrapper.eq("id", exist.getId());
                updateWrapper.setSql("clock_in_number=clock_in_number+1");
                SubjectClockInDO update = new SubjectClockInDO();
                //开启乐观锁功能
                update.setVersion(exist.getVersion());
                result = subjectClockInDao.update(update, updateWrapper);
            } else {
                SubjectClockInDO save = new SubjectClockInDO();
                save.setSubjectId(subjectId);
                save.setName(subjectClockIn.getName());
                save.setClockInNumber(0L);
                result = subjectClockInDao.insert(save);
            }
            if (result <= 0) {
                throw new BdException("操作失败！");
            }
            return ResultVo.ok();
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ResultVo.error();
    }

}
